use crate::srt::SrtLine;
use chrono::Utc;
use napi_derive_ohos::napi;
use rsubs_lib::SRT;
use std::{fs::File, io::Read};

#[napi]
pub struct ParseSrt {
    path: String,
    instance: Option<SRT>,
}

#[napi]
impl ParseSrt {
    #[napi(constructor)]
    pub fn new(path: String) -> Self {
        ParseSrt {
            path,
            instance: None,
        }
    }

    #[napi]
    pub async unsafe fn init(&mut self) {
        if let Ok(mut file) = File::open(&self.path) {
            let mut contents = String::new();
            if let Ok(_) = file.read_to_string(&mut contents) {
                if let Ok(result) = SRT::parse(contents) {
                    self.instance = Some(result);
                }
            }
        }
    }

    #[napi]
    pub async unsafe fn read_lines(&mut self) -> Vec<SrtLine> {
        let mut list: Vec<SrtLine> = vec![];
        if let Some(result) = &self.instance {
            for line in &result.lines {
                let start_opt =
                    chrono::DateTime::<Utc>::from_timestamp_millis(line.start.millisecond().into());
                let end_opt =
                    chrono::DateTime::<Utc>::from_timestamp_millis(line.end.millisecond().into());
                match (start_opt, end_opt) {
                    (Some(start), Some(end)) => {
                        list.push(SrtLine {
                            sequence_number: line.sequence_number,
                            start_timestamp_millis: start.timestamp_millis(),
                            end_timestamp_millis: end.timestamp_millis(),
                            text: line.text.to_string(),
                        });
                    }
                    _ => {}
                }
            }
        }
        list
    }
}
